package ssen.mvc.base {
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;

import ssen.mvc.core.ICommand;
import ssen.mvc.core.ICommandMap;
import ssen.mvc.core.IInjector;

public class CommandMap implements ICommandMap {
	private var dic:Dictionary;
	private var injector:IInjector;
	private var dispatcher:IEventDispatcher;

	public function CommandMap(dispatcher:IEventDispatcher, injector:IInjector) {
		this.dispatcher=dispatcher;
		this.injector=injector;
		dic=new Dictionary;
	}

	public function mapCommand(eventType:String, commandClass:Class):void {
		if (dic[eventType] !== undefined) {
			throw new Error("mapped this event type");
		}

		dic[eventType]=commandClass;
		dispatcher.addEventListener(eventType, eventCatched);
	}

	private function eventCatched(event:Event):void {
		var command:ICommand=create(event.type);
		command.execute(event);
	}

	public function unmapCommand(eventType:String):void {
		if (dic[eventType] === undefined) {
			throw new Error("undefined this command type");
		}

		delete dic[eventType];
		dispatcher.removeEventListener(eventType, eventCatched);
	}

	public function hasMapping(eventType:String):Boolean {
		return dic[eventType] !== undefined;
	}

	private function create(eventType:String):ICommand {
		if (dic[eventType] === undefined) {
			throw new Error("undefined command");
		}

		var commandClass:Class=dic[eventType];
		var command:ICommand=new commandClass();

		injector.injectInto(command);

		return command;
	}

	public function dispose():void {
		dic=null;
	}
}
}
